package com.wondersgroup.fjzlpt.tbxt.service.impl.yltfwtz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.ExcelOrWordUtils;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.tbxt.dao.inter.tz.YltfwtzDAO;
import com.wondersgroup.fjzlpt.tbxt.service.inter.yltfwtz.YltfwtzService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 医联体服务实现层
 * <p>
 * <p>
 * Created by sanma on 2017/9/18.
 */
@Service
public class YltfwtzServiceImpl implements YltfwtzService{

    @Autowired
    private YltfwtzDAO yltfwtzDAO ;

    /**
     * 批量保存
     * @param map
     * @return
     */
    public JSONObject save(Map map){
        JSONObject result = new JSONObject();
        try{
            String type = map.remove("type").toString();
            if("add".equals(type)){
                this.insertBatch(map);
                result.put("info","保存成功!");
            }else{
                this.update(map);
                result.put("info","修改成功!");
            }
            result.put("state","true");
        }catch (Exception e){
            result.put("info","保存失败，请稍后再试!");
            throw new RuntimeException("保存失败，请稍后再试!");
        }
        return result;
    }

    /**
     * 批量保存
     * @param map
     */
    public void insertBatch(Map<String,Object> map){
        map.put("ADD_USERID",map.remove("USERID"));
        map.put("ADD_USERNAME",map.remove("USERNAME"));
        map.put("XZSJ",new Date()); //新增时间

        List<Map> listMaps = new ArrayList<Map>();

        String rows = map.remove("rows").toString();
        if(!StringUtils.isEmpty(rows)){
            JSONArray rowsArr = JSONArray.parseArray(rows);
            for(Object item : rowsArr){
                JSONObject itemObj = (JSONObject)item;
                itemObj.put("ID", UUID.randomUUID().toString());
                itemObj.putAll(map); //map中还包含：PTJGID、JGMC,XZSJ等其他字段。
                itemObj.put("FWSJ", FormatDate.getDateY_M_D(itemObj.getString("FWSJ")));
                listMaps.add(itemObj);
            }
        }
        yltfwtzDAO.insertBatch(listMaps);
    }

    /**
     * 修改
     * @param map
     */
    public void update(Map map){
        //删除不可更新的字段
        map.remove("PTJGID");
        map.remove("JGMC");
        map.remove("JGLB");
        map.remove("XZQHDM");

        map.put("FWSJ", FormatDate.getDateY_M_D(map.get("FWSJ").toString()));
        map.put("UPDATE_USERID",map.remove("USERID"));
        map.put("UPDATE_USERNAME",map.remove("USERNAME"));
        map.put("GXSJ",new Date()); //更新时间
        yltfwtzDAO.updateForPrimaryKey(map);
    }

    /**
     * 分页查询
     * @param map
     * @return
     */
    public JSONObject queryPage(Map map){
        return yltfwtzDAO.queryPage(map);
    }

    /**
     * 根据主键ID删除数据（不可恢复）
     * @param map
     * @return
     */
    public JSONObject delete(Map map){
        JSONObject result = new JSONObject();
        try {
            yltfwtzDAO.deleteForPrimaryKey(map);
            result.put("info","删除成功!");
            result.put("state","true");
        }catch (Exception e){
            result.put("info","删除数据失败，请稍后再试!");
            throw new RuntimeException("删除数据失败，请稍后再试!");
        }
        return result;
    }

    /**
     * 下载Excel模板
     * @param response
     */
    public void downExcelModel(HttpServletRequest request, HttpServletResponse response){
        JSONArray downData = new JSONArray();

        //表头
        StringBuffer titleStr = new StringBuffer();
        titleStr.append("{'a':'服务时间','b':'服务名称','c':'服务内容','d':'提供服务机构','e':'接收服务机构','f':'医联体类型'}");
        JSONObject title = JSONObject.parseObject(titleStr.toString());
        downData.add(0, title);

        //排列循序
        List<String> titelField = new ArrayList<>();
        titelField.add("a");
        titelField.add("b");
        titelField.add("c");
        titelField.add("d");
        titelField.add("e");
        titelField.add("f");
        ExcelOrWordUtils.downLoadExcelFile(downData, titelField ,"医联体服务台账-模板",request, response);
    }

    /**
     * 解析上传的Excel数据
     * @param request
     * @return
     */
    public String parseExcalData(MultipartFile file, HttpServletRequest request){
        String[] title = new String[] { "服务时间","服务名称", "服务内容", "提供服务机构", "接收服务机构",
                "医联体类型"};
        String[] titleField = new String[]{ "FWSJ","FWMC", "FWNR", "TGFWJG", "JSFWJG", "YLTLX"};
        JSONObject result = new JSONObject();
        try {
            result = ExcelOrWordUtils.parseExcalData(file.getInputStream(), title, titleField);
            if(result.getBoolean("state") && result.getJSONArray("data").size()>100){
                result.remove("data");
                result.remove("state");
                result.put("info","导入文件数据量请控制在100条以内!");
            }
        }catch (Exception e){
            LoggerUtil.error(e.getMessage());
            throw new ServiceException("ERR-002001" , "Excel文件解析出错，请稍后再试!");
        }
        return result.toString();
    }
}
